<template>
  <div id="match">
    <!-- 比赛区域 -->
    <section v-if="isMatchWaitingToAccept">
      <el-card class="opt-card-cell">
        <el-button style="float: right;margin-top:0px;" type="danger" @click="onAcceptChallenge">Accept challenge</el-button>
      </el-card>
    </section>
    <section v-if="isWaiting">
      <div class="h-center" style="margin-top: 40px;">
        Wait opponent to accept challenge...
      </div>
    </section>
    <section v-show="isMatchNeedToDisplay">
      <div v-show="isMatchPlaying" class="h-center" style="margin-top: 40px;">
        <video id="myVideo" ref="myVideo" :src="videoSrc" :poster="videoImg" height="414" width="720">
            your browser does not support the video tag
        </video>
      </div>

      <div v-if="isMatchFinish" class="h-center" style="margin-top: 40px;">
        <div v-if="isMatchSucceed"></div>
        <div v-if="isMatchFail"></div>
      </div>
    </section>

    <!-- 对话框 -->
    <el-dialog
    title=""
    :visible.sync="succeedDialogVisible"
    width="30%">
    <span>Congratulations! You won the race. Opponent's bets 10 HSD is now yours.</span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="onSucceedProceed">Find another opponent</el-button>
        <el-button type="info" @click="onSucceedConfirmed">OK</el-button>
    </span>
    </el-dialog>

    <el-dialog
    title=""
    :visible.sync="failDialogVisible"
    width="30%">
    <span>Sorry...Luck is not on your side this time.</span>
    <span slot="footer" class="dialog-footer">
        <el-button @click="onFailProceed">Find another opponent</el-button>
        <el-button type="info" @click="onFailConfirmed">OK</el-button>
    </span>
    </el-dialog>

    <!-- 发起挑战 对话框 -->
    <el-dialog
    title=""
    :visible.sync="startChallengeDialogVisible"
    width="60%">
    <span
      class="h-justify v-center">
      <span>
        <div>Your Horse</div>
        <el-card :body-style="{ padding: '0px' }" class="card-cell h-center">
          <ve-radar
            width="280px"
            height="220px"
            :data="fromHorse.chartData"
            :settings="chartSettings"
            :tooltip-visible="false"
            :legend-visible="true"
            :colors="colors"
            :extend="extend"
            class="skill-charts"></ve-radar>

          <el-rate
            v-model="fromHorse.rateValue"
            disabled
            class="rate">
          </el-rate>

          <div class="card-bottom h-justify">
            <img class="circle" :src="fromHorse.imgUrl" width="100px" height="100px">
            <span class="v-bottom" style="color: #00ff00;">
              <div>{{ fromHorse.name }}</div>
            </span>
            <span class="trailing-4 v-bottom">
              <div >Gen{{fromHorse.generationNum}}</div>
            </span>
          </div>
        </el-card>
      </span>

      <span>
        VS
        <div>
          Bets: 10 HSD
        </div>
      </span>

      <span>
        <div>Opponent</div>
        <el-card :body-style="{ padding: '0px' }" class="card-cell h-center">
          <ve-radar
            width="280px"
            height="220px"
            :data="toHorse.chartData"
            :settings="chartSettings"
            :tooltip-visible="false"
            :legend-visible="true"
            :colors="colors"
            :extend="extend"
            class="skill-charts"></ve-radar>

          <el-rate
            v-model="toHorse.rateValue"
            disabled
            class="rate">
          </el-rate>

          <div class="card-bottom h-justify">
            <img class="circle" :src="toHorse.imgUrl" width="100px" height="100px">
            <span class="v-bottom" style="color: #00ff00;">
              <div>{{ toHorse.name }}</div>
            </span>
            <span class="trailing-4 v-bottom">
              <div >Gen{{toHorse.generationNum}}</div>
            </span>
          </div>
        </el-card>
      </span>
    </span>
    <span slot="footer" class="dialog-footer">
      <el-button type="success" @click="onAcceptChallengeConfirmed">Accept</el-button>
    </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'match',
    data: function () {
      this.extend = {
        series: {
          label: {
            normal: {
              show: true
            }
          }
        }
      }

      this.chartSettings = {
        dimension: [],
        metrics: ['Speed', 'Acceleration', 'Strength', 'Endurance', 'Agile', 'Balancing', 'Bouncing'],
        dataType: 'normal'
      }

      this.colors = [
        '#00000000',
        '#2f4554'
      ]

      return {
        isChallenger: false,
        // 1. 挑战者：等待接受 isWaiting
        // 2. 被挑战者：接受比赛 isMatchWaitingToAccept

        fromHorse: {},
        toHorse: {},
        fromHorseId: 0,
        toHorseId: 0,

        walletAddress: '',

        matchId: 0,
        matchDetail: {},

        isValid: true,
        isWaiting: false,
        isRunning: false,
        isMatchPlaying: false,
        isMatchStoped: false,
        isMatchFinish: false, // 获取比赛结果

        isMatchFail: false,
        isMatchSucceed: false,

        isMatchWaitingToAccept: false,
        isMatchNeedToDisplay: false,

        succeedDialogVisible: false,
        failDialogVisible: false,
        rejectDialogVisible: false,
        startChallengeDialogVisible: false,

        playStatus: '',
        videoSrc: 'http://babylife.qiniudn.com/FtRVyPQHHocjVYjeJSrcwDkApTLQ',
        videoImg: 'http://static.fdc.com.cn/avatar/usercenter/5996999fa093c04d4b4dbaf1_162.jpg',

        imgUrl: ''
      }
    },
    mounted () {
      this.isChallenger = this.$route.query.isChallenger
      this.matchId = this.$route.query.id

      console.log('Match id = ' + this.matchId + ', is = ' + this.isChallenger)

      this.imgUrl = require('../../assets/img/user/head.jpg')

      this.getUserInfo()
    },
    beforeRouteLeave (to, from, next) {
      clearTimeout(window.timer)
      next()
    },
    methods: {
      onAcceptChallengeConfirmed () {
        this.startChallengeDialogVisible = false

        this.$root.callMatch({
          isProtected: false,
          params: parseInt(this.matchId),
          methodName: API.ACCEPT_CHALLENGE,
          methodType: 'POST',
          event: 'MatchFinish',
          success: data => {
            console.log(JSON.stringify(data))
            this.acceptChallengeResult = data

            // 获取结果
          },
          failure: null
        })
      },
      onAcceptChallenge () {
        this.startChallengeDialogVisible = true

        this.$root.callMatch({
          isProtected: false,
          params: this.matchDetail.tokenFrom,
          methodName: API.GET_HORSE,
          methodType: 'GET',
          success: data => {
            console.log(JSON.stringify(data))
            var gen = data[0] // 基因
            var speedValue = parseInt(gen.slice(0, 2))
            var accelerationValue = parseInt(gen.slice(2, 4))
            var strengthValue = parseInt(gen.slice(4, 6))
            var enduranceValue = parseInt(gen.slice(6, 8))
            var agileValue = parseInt(gen.slice(8, 10))
            var balancingValue = parseInt(gen.slice(10, 12))
            var bouncingValue = parseInt(gen.slice(12, 14))
            var reactionValue = parseInt(gen.slice(14, 16))

            var generationNum = data[7]

            var horse = {}

            horse.id = this.matchDetail.tokenFrom
            horse.name = HORSE_NAMES[horse.id]
            horse.imgUrl = require(`../../assets/img/horses/${this.matchDetail.tokenFrom}.jpg`)
            horse.chartData = {
              rows: [
                { 'Speed': 100,
                  'Acceleration': 100,
                  'Strength': 100,
                  'Endurance': 100,
                  'Agile': 100,
                  'Balancing': 100,
                  'Bouncing': 100,
                  'Reaction': 100
                },
                {
                  'Speed': speedValue,
                  'Acceleration': accelerationValue,
                  'Strength': strengthValue,
                  'Endurance': enduranceValue,
                  'Agile': agileValue,
                  'Balancing': balancingValue,
                  'Bouncing': bouncingValue,
                  'Reaction': reactionValue
                }
              ]
            }

            var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
            horse.rateValue = Math.ceil(rateValue)

            horse.generationNum = parseInt(generationNum)

            this.fromHorse = horse
          },
          failure: null
        })

        this.$root.callMatch({
          isProtected: false,
          params: this.matchDetail.tokenTo,
          methodName: API.GET_HORSE,
          methodType: 'GET',
          success: data => {
            console.log(JSON.stringify(data))
            var gen = data[0] // 基因
            var speedValue = parseInt(gen.slice(0, 2))
            var accelerationValue = parseInt(gen.slice(2, 4))
            var strengthValue = parseInt(gen.slice(4, 6))
            var enduranceValue = parseInt(gen.slice(6, 8))
            var agileValue = parseInt(gen.slice(8, 10))
            var balancingValue = parseInt(gen.slice(10, 12))
            var bouncingValue = parseInt(gen.slice(12, 14))
            var reactionValue = parseInt(gen.slice(14, 16))

            var generationNum = data[7]

            var horse = {}

            horse.id = this.matchDetail.tokenTo
            horse.name = HORSE_NAMES[horse.id]
            horse.imgUrl = require(`../../assets/img/horses/${this.matchDetail.tokenTo}.jpg`)
            horse.chartData = {
              rows: [
                { 'Speed': 100,
                  'Acceleration': 100,
                  'Strength': 100,
                  'Endurance': 100,
                  'Agile': 100,
                  'Balancing': 100,
                  'Bouncing': 100,
                  'Reaction': 100
                },
                {
                  'Speed': speedValue,
                  'Acceleration': accelerationValue,
                  'Strength': strengthValue,
                  'Endurance': enduranceValue,
                  'Agile': agileValue,
                  'Balancing': balancingValue,
                  'Bouncing': bouncingValue,
                  'Reaction': reactionValue
                }
              ]
            }

            var rateValue = (speedValue + accelerationValue + strengthValue + enduranceValue + agileValue + balancingValue + bouncingValue + reactionValue) / 160
            horse.rateValue = Math.ceil(rateValue)

            horse.generationNum = parseInt(generationNum)

            this.toHorse = horse
          },
          failure: null
        })
      },
      handleDialogClose () {

      },
      onSucceedProceed () {
        this.isValid = false
        this.succeedDialogVisible = false

        this.$router.replace({
          path: '/market',
          query: {}
        })
      },
      onFailConfirmed () {
        this.isValid = false
        this.failDialogVisible = false
      },
      onFailProceed () {
        this.isValid = false
        this.failDialogVisible = false

        this.$router.replace({
          path: '/market',
          query: {}
        })
      },
      onSucceedConfirmed () {
        this.isValid = false
        this.succeedDialogVisible = false
      },
      timer: function () {
        if (!this.isValid) {
          return
        }

        this.getMatchDetail(parseInt(this.matchId))
      },
      handleMatchStateUpdated () {
        if (this.isRunning && !this.isMatchPlaying) {
          var vdo = this.$refs.myVideo
          vdo.play()

          this.isMatchPlaying = true
        }

        if (this.isMatchPlaying) {
          vdo = this.$refs.myVideo // document.getElementById('videoPlay')

          this.flag = vdo.paused

          if (this.flag) {
            // 展示比赛结果
            this.isValid = false

            // 比赛结果
            this.$root.callMatch({
              isProtected: false,
              params: parseInt(this.matchId),
              methodName: API.GET_MATCH_RESULT,
              methodType: 'GET',
              success: data => {
                console.log(JSON.stringify(data))

                // int 比赛使用的随机数
                // int score_from 发起方的最终得分
                // int score_to 接受挑战方的得分
                // int 结束时间
                // address 获胜方
                // int gain 获利金额

                if (data[4] === this.walletAddress) {
                  this.isMatchSucceed = true
                  this.succeedDialogVisible = true
                } else {
                  this.isMatchFail = true
                  this.failDialogVisible = true
                }
              },
              failure: null
            })
          }
        }
      },
      getUserInfo () {
        console.log('get user info...')

        // 查询用户信息
        this.$root.callMatch({
          params: null,
          methodName: API.GET_ACCOUNTS,
          methodType: 'GET',
          success: (data) => {
            console.log('walletAddress = ' + data)

            this.walletAddress = data

            // 开始轮询比赛状态
            this.$nextTick(function () {
              setInterval(this.timer, 4000)
            })
          },
          failure: null
        })
      },
      getMatchDetail (matchIdInt) {
        this.$root.callMatch({
          isProtected: false,
          params: matchIdInt,
          methodName: API.GET_MATCH_DETAIL,
          methodType: 'GET',
          success: data => {
            console.log('GET_MATCH_DETAIL = ' + JSON.stringify(data))

            // address from, address to, int token_from, int token_to, int 赌注, int 阶段, int 比赛id
            this.matchDetail = {
              from: data[0], // 如果是我 则 我挑战别人
              to: data[1], // 如果是我，则 别人挑战我
              tokenFrom: parseInt(data[2]),
              tokenTo: parseInt(data[3]),
              wager: data[4],
              status: parseInt(data[5]),
              id: data[6]
            }

            // 判断被挑战者
            if (parseInt(this.isChallenger) === 0) {
              var id = this.matchDetail.tokenFrom
              this.matchDetail.tokenFrom = this.matchDetail.tokenTo
              this.matchDetail.tokenTo = id
            }

            if (this.matchDetail.status === 2) { // 不接受
              this.isMatchNeedToDisplay = true
            } else if (this.matchDetail.status === 4) { // 结束, 获取比赛结果
              this.isRunning = true
              this.isMatchNeedToDisplay = true
            }

            if (this.matchDetail.to === this.walletAddress) { // 被挑战
              if (this.matchDetail.status === 1) {
                this.isMatchWaitingToAccept = true
              } else {
                this.isMatchWaitingToAccept = false
              }
            } else { // 挑战
              if (this.matchDetail.status === 1) {
                this.isWaiting = true
              } else {
                this.isWaiting = false
              }
            }

            this.handleMatchStateUpdated()
          },
          failure: null
        })
      }
    }
  }

  import { API, HORSE_NAMES } from '../../util/constants'
</script>

<style scoped>
#match {
  width: 100%;
  height: 420px;
  margin-top: 78px;
  margin-left: 12px;
}

.profile-info-cell {
  height: 120px;
  width: 100%;
}

.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}

.clearfix:after {
  clear: both
}

.card-cell {
  height: 344px;
}

.card-col {
  width: 20%;
}

.card-bottom {
  margin-top: 2px;
}

.skill-charts {
  /* padding-top: 0; */
  /* margin-top: 0; */
  /* width: 100%; */
  /* margin-top: -20px; */
  /* height: 200px; */
  max-height: 290px;
  max-width: 380px;
  /* margin: 10px; */
}

.card-down {
  bottom: 0px;
}

.rate-cell {
  margin-top: 10px;
}

.opt-card-cell {
    margin-top: 20px;
    width: 65%;
    height: 120px;
}

</style>
